package cn.feuler.gateway.filter;

import cn.feuler.gateway.client.UserClient;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.Set;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    private static Set<String> whiteList = Sets.newHashSet(
            "/api/user/login",
            "/api/user/isRegistered",
            "/api/user/register",
            "/api/code/create"
    );

    private final UserClient userClient;

    public TokenFilter(@Qualifier("cn.feuler.gateway.client.UserClient") UserClient userClient) {
        this.userClient = userClient;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        for (String s : whiteList) {
            if (path.startsWith(s)) {
                return chain.filter(exchange);
            }
        }
        ServerHttpRequest request = exchange.getRequest();
        HttpCookie token = request.getCookies().getFirst("token");
        HttpCookie email = request.getCookies().getFirst("email");

        if (Objects.nonNull(email) && Objects.nonNull(token)) {
            String tokenEmail = userClient.info(token.getValue());
            String cookieEmail = email.getValue();
            if (tokenEmail.equalsIgnoreCase(cookieEmail)) {
                return chain.filter(exchange);
            }
        }

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        response.getHeaders().add("Location", "/login.html");
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
